package common

import (
	"errors"
	
	"soma-server/config"
	system "soma-server/model/system"
	"soma-server/pkg/util"

	"github.com/thoas/go-funk"
	"gorm.io/gorm"
)

// 初始化mysql数据
func InitData() {
	var uint0 uint = 0
	var uint1 uint = 1
	var uint2 uint = 2
	var uint7 uint = 7
	var boolTrue bool = true
	var boolFalse bool = false
	// 是否初始化数据
	if !config.Conf.System.InitData {
		return
	}

	// 1.写入菜单
	newMenus := make([]system.Menu, 0)
	systemManageIcon := "ep:tools"
	systemManageName := "SystemParent"
	userManageIcon := "ep:user-filled"
	userManageName := "Users"
	menuManageIcon := "ep:menu"
	menuManageName := "Menus"
	roleManageIcon := "fa-solid:key"
	roleManageName := "Roles"
	apiManageIcon := "ep:document"
	apiManageName := "Apis"
	logManageIcon := "fa:newspaper-o"
	logManageName := "Logs"
	profileManageIcon := ""
	profileManageName := "ProfileParent"
	personalManageIcon := ""
	personalManageName := "Profile"
	menus := []system.Menu{
		{
			Model: gorm.Model{ID: 1},
			Name:  &systemManageName,
			Path:  "/system",
			Meta: system.Meta{
				Title:      "系统管理",
				Icon:       &systemManageIcon,
				Rank:       10,
				ShowLink:   &boolTrue,
				KeepAlive:  &boolTrue,
				ShowParent: &boolTrue,
				HiddenTag:  &boolFalse,
			},
			Redirect: new(string),
			ParentId: &uint0,
			Type:     uint1,
			Creator:  "系统",
		},
		{
			Model: gorm.Model{ID: 2},
			Name: &userManageName,
			Path: "/system/users/index",
			Meta: system.Meta{
				Title:      "用户管理",
				Icon:       &userManageIcon,
				Rank:       20,
				ShowLink:   &boolTrue,
				KeepAlive:  &boolTrue,
				ShowParent: &boolTrue,
				HiddenTag:  &boolFalse,
			},
			Redirect: new(string),
			ParentId: &uint1,
			Type:     uint2,
			Creator:  "系统",
		},
		{
			Model: gorm.Model{ID: 3},
			Name: &menuManageName,
			Path: "/system/menus/index",
			Meta: system.Meta{
				Title:      "菜单管理",
				Icon:       &menuManageIcon,
				Rank:       21,
				ShowLink:   &boolTrue,
				KeepAlive:  &boolTrue,
				ShowParent: &boolTrue,
				HiddenTag:  &boolFalse,
			},
			Redirect: new(string),
			ParentId: &uint1,
			Type:     uint2,
			Creator:  "系统",
		},
		{
			Model: gorm.Model{ID: 4},
			Name: &roleManageName,
			Path: "/system/roles/index",
			Meta: system.Meta{
				Title:      "角色管理",
				Icon:       &roleManageIcon,
				Rank:       22,
				ShowLink:   &boolTrue,
				KeepAlive:  &boolTrue,
				ShowParent: &boolTrue,
				HiddenTag:  &boolFalse,
			},
			Redirect: new(string),
			ParentId: &uint1,
			Type:     uint2,
			Creator:  "系统",
		},
		{
			Model: gorm.Model{ID: 5},
			Name: &apiManageName,
			Path: "/system/apis/index",
			Meta: system.Meta{
				Title:      "接口管理",
				Icon:       &apiManageIcon,
				Rank:       23,
				ShowLink:   &boolTrue,
				KeepAlive:  &boolTrue,
				ShowParent: &boolTrue,
				HiddenTag:  &boolFalse,
			},
			Redirect: new(string),
			ParentId: &uint1,
			Type:     uint2,
			Creator:  "系统",
		},
		{
			Model: gorm.Model{ID: 6},
			Name: &logManageName,
			Path: "/system/logs/index",
			Meta: system.Meta{
				Title:      "操作日志",
				Icon:       &logManageIcon,
				Rank:       24,
				ShowLink:   &boolTrue,
				KeepAlive:  &boolTrue,
				ShowParent: &boolTrue,
				HiddenTag:  &boolFalse,
			},
			Redirect: new(string),
			ParentId: &uint1,
			Type:     uint2,
			Creator:  "系统",
		},
		{
			Model: gorm.Model{ID: 7},
			Name: &profileManageName,
			Path: "/profile",
			Meta: system.Meta{
				Title:      "用户中心",
				Icon:       &profileManageIcon,
				Rank:       30,
				ShowLink:   &boolFalse,
				KeepAlive:  &boolTrue,
				ShowParent: &boolTrue,
				HiddenTag:  &boolFalse,
			},
			Redirect: new(string),
			ParentId: &uint0,
			Type:     uint1,
			Creator:  "系统",
		},
		{
			Model: gorm.Model{ID: 8},
			Name: &personalManageName,
			Path: "/profile/index",
			Meta: system.Meta{
				Title:      "个人中心",
				Icon:       &personalManageIcon,
				Rank:       31,
				ShowLink:   &boolFalse,
				KeepAlive:  &boolTrue,
				ShowParent: &boolTrue,
				HiddenTag:  &boolFalse,
			},
			Redirect: new(string),
			ParentId: &uint7,
			Type:     uint2,
			Creator:  "系统",
		},
	}
	for _, menu := range menus {
		err := DB.First(&menu, menu.ID).Error
		if errors.Is(err, gorm.ErrRecordNotFound) {
			newMenus = append(newMenus, menu)
		}
	}
	if len(newMenus) > 0 {
		err := DB.Create(&newMenus).Error
		if err != nil {
			Log.Errorf("写入系统菜单数据失败：%v", err)
		}
	}

	// 2.写入角色数据
	newRoles := make([]*system.Role, 0)
	adminRoleMenus := make([]*system.Menu, 0)
	otherRoleMenu := make([]*system.Menu, len(menus))

	for _, menu := range menus {
		copyMenu := menu
		adminRoleMenus = append(adminRoleMenus, &copyMenu)
	}

	err := copy(otherRoleMenu, adminRoleMenus)
	if err == 0 {
		Log.Errorln("复制菜单信息失败")
	}

	roles := []*system.Role{
		{
			Model:   gorm.Model{ID: 1},
			Name:    "管理员",
			Code:    "admin",
			Remark:  new(string),
			Sort:    1,
			Status:  1,
			Creator: "系统",
			Menus: adminRoleMenus[:],
		},
		{
			Model:   gorm.Model{ID: 2},
			Name:    "访客角色",
			Code:    "guest",
			Remark:  new(string),
			Sort:    100,
			Status:  1,
			Creator: "系统",
			Menus: otherRoleMenu[len(otherRoleMenu)-2:],
		},
	}

	for _, role := range roles {
		err := DB.First(&role, role.ID).Error
		if errors.Is(err, gorm.ErrRecordNotFound) {
			newRoles = append(newRoles, role)
		}
	}

	if len(newRoles) > 0 {
		err := DB.Create(&newRoles).Error
		if err != nil {
			Log.Errorf("写入系统角色数据失败：%v", err)
		}
	}

	// 3.写入用户
	newUsers := make([]system.User, 0)
	users := []system.User{
		{
			Model:    gorm.Model{ID: 1},
			Username: "admin",
			Password: util.GenPasswd("123456aa"),
			Mobile:   "18888888888",
			Avatar:   new(string),
			Nickname: new(string),
			Remark:   new(string),
			Status:   1,
			Creator:  "系统",
			Roles:    roles[:1],
		},
	}

	for _, user := range users {
		err := DB.First(&user, user.ID).Error
		if errors.Is(err, gorm.ErrRecordNotFound) {
			newUsers = append(newUsers, user)
		}
	}

	if len(newUsers) > 0 {
		err := DB.Create(&newUsers).Error
		if err != nil {
			Log.Errorf("写入用户数据失败：%v", err)
		}
	}

	// 4.写入api
	apis := []system.Api{
		{
			Method:   "POST",
			Path:     "/base/login",
			Category: "base",
			Desc:     "用户登录",
			Creator:  "系统",
		},
		{
			Method:   "POST",
			Path:     "/base/refreshToken",
			Category: "base",
			Desc:     "刷新JWT令牌",
			Creator:  "系统",
		},
		{
			Method:   "GET",
			Path:     "/user/info",
			Category: "user",
			Desc:     "获取当前登录用户信息",
			Creator:  "系统",
		},
		{
			Method:   "POST",
			Path:     "/user/list",
			Category: "user",
			Desc:     "获取用户列表",
			Creator:  "系统",
		},
		{
			Method:   "PUT",
			Path:     "/user/changePwd",
			Category: "user",
			Desc:     "更新用户登录密码",
			Creator:  "系统",
		},
		{
			Method:   "POST",
			Path:     "/user/create",
			Category: "user",
			Desc:     "创建用户",
			Creator:  "系统",
		},
		{
			Method:   "PUT",
			Path:     "/user/update/:userId",
			Category: "user",
			Desc:     "更新用户",
			Creator:  "系统",
		},
		{
			Method:   "DELETE",
			Path:     "/user/delete/batch",
			Category: "user",
			Desc:     "批量删除用户",
			Creator:  "系统",
		},
		{
			Method:   "POST",
			Path:     "/role/list",
			Category: "role",
			Desc:     "获取角色列表",
			Creator:  "系统",
		},
		{
			Method:   "GET",
			Path:     "/role/options",
			Category: "role",
			Desc:     "获取角色下拉列表选项",
			Creator:  "系统",
		},
		{
			Method:   "POST",
			Path:     "/role/create",
			Category: "role",
			Desc:     "创建角色",
			Creator:  "系统",
		},
		{
			Method:   "PUT",
			Path:     "/role/update/:roleId",
			Category: "role",
			Desc:     "更新角色",
			Creator:  "系统",
		},
		{
			Method:   "GET",
			Path:     "/role/menus/get/:roleId",
			Category: "role",
			Desc:     "获取角色的权限菜单",
			Creator:  "系统",
		},
		{
			Method:   "PUT",
			Path:     "/role/menus/update/:roleId",
			Category: "role",
			Desc:     "更新角色的权限菜单",
			Creator:  "系统",
		},
		{
			Method:   "GET",
			Path:     "/role/apis/get/:roleId",
			Category: "role",
			Desc:     "获取角色的权限接口",
			Creator:  "系统",
		},
		{
			Method:   "PUT",
			Path:     "/role/apis/update/:roleId",
			Category: "role",
			Desc:     "更新角色的权限接口",
			Creator:  "系统",
		},
		{
			Method:   "DELETE",
			Path:     "/role/delete/batch",
			Category: "role",
			Desc:     "批量删除角色",
			Creator:  "系统",
		},
		{
			Method:   "GET",
			Path:     "/menu/list",
			Category: "menu",
			Desc:     "获取菜单列表",
			Creator:  "系统",
		},
		{
			Method:   "GET",
			Path:     "/menu/tree",
			Category: "menu",
			Desc:     "获取菜单树",
			Creator:  "系统",
		},
		{
			Method:   "POST",
			Path:     "/menu/create",
			Category: "menu",
			Desc:     "创建菜单",
			Creator:  "系统",
		},
		{
			Method:   "PUT",
			Path:     "/menu/update/:menuId",
			Category: "menu",
			Desc:     "更新菜单",
			Creator:  "系统",
		},
		{
			Method:   "DELETE",
			Path:     "/menu/delete/batch",
			Category: "menu",
			Desc:     "批量删除菜单",
			Creator:  "系统",
		},
		{
			Method:   "GET",
			Path:     "/menu/access/list/:userId",
			Category: "menu",
			Desc:     "获取用户的可访问菜单列表",
			Creator:  "系统",
		},
		{
			Method:   "GET",
			Path:     "/menu/access/tree/:userId",
			Category: "menu",
			Desc:     "获取用户的可访问菜单树",
			Creator:  "系统",
		},
		{
			Method:   "POST",
			Path:     "/menu/tree/search",
			Category: "menu",
			Desc:     "获取菜单搜索结果",
			Creator:  "系统",
		},
		{
			Method:   "POST",
			Path:     "/api/list",
			Category: "api",
			Desc:     "获取接口列表",
			Creator:  "系统",
		},
		{
			Method:   "GET",
			Path:     "/api/tree",
			Category: "api",
			Desc:     "获取接口树",
			Creator:  "系统",
		},
		{
			Method:   "POST",
			Path:     "/api/create",
			Category: "api",
			Desc:     "创建接口",
			Creator:  "系统",
		},
		{
			Method:   "PUT",
			Path:     "/api/update/:roleId",
			Category: "api",
			Desc:     "更新接口",
			Creator:  "系统",
		},
		{
			Method:   "DELETE",
			Path:     "/api/delete/batch",
			Category: "api",
			Desc:     "批量删除接口",
			Creator:  "系统",
		},
		{
			Method:   "POST",
			Path:     "/log/operation/list",
			Category: "log",
			Desc:     "获取操作日志列表",
			Creator:  "系统",
		},
		{
			Method:   "DELETE",
			Path:     "/log/operation/delete/batch",
			Category: "log",
			Desc:     "批量删除操作日志",
			Creator:  "系统",
		},
	}
	newApi := make([]system.Api, 0)
	newRoleCasbin := make([]system.RoleCasbin, 0)
	for i, api := range apis {
		api.ID = uint(i + 1)
		err := DB.First(&api, api.ID).Error
		if errors.Is(err, gorm.ErrRecordNotFound) {
			newApi = append(newApi, api)

			// 管理员拥有所有API权限
			newRoleCasbin = append(newRoleCasbin, system.RoleCasbin{
				Code:   roles[0].Code,
				Path:   api.Path,
				Method: api.Method,
			})

			// 目前只测试管理员，先注释掉其他
			// 非管理员拥有基础权限
			basePaths := []string{
				"/base/login",
				"/base/refreshToken",
				"/user/info",
				"/menu/access/tree/:userId",
			}

			if funk.ContainsString(basePaths, api.Path) {
				newRoleCasbin = append(newRoleCasbin, system.RoleCasbin{
					Code:   roles[1].Code,
					Path:   api.Path,
					Method: api.Method,
				})
			}
		}
	}

	if len(newApi) > 0 {
		if err := DB.Create(&newApi).Error; err != nil {
			Log.Errorf("写入api数据失败：%v", err)
		}
	}

	if len(newRoleCasbin) > 0 {
		rules := make([][]string, 0)
		for _, c := range newRoleCasbin {
			rules = append(rules, []string{
				c.Code, c.Path, c.Method,
			})
		}
		isAdd, err := CasbinEnforcer.AddPolicies(rules)
		if !isAdd {
			Log.Errorf("写入casbin数据失败：%v", err)
		}
	}
}
